package com.xmlt.ui.launcher;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import ognl.OgnlException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;

import com.xmlt.core.template.Template;
import com.xmlt.core.template.TemplateException;
import com.xmlt.core.template.TemplateSection;
import com.xmlt.core.template.instance.Instance;
import com.xmlt.ui.builder.BuilderPlugin;
import com.xmlt.ui.builder.XMLTNature;

public class LaunchconfigurationDelegate implements
		ILaunchConfigurationDelegate {

	@Override
	public void launch(ILaunchConfiguration configuration, String mode,
			ILaunch launch, IProgressMonitor monitor) throws CoreException {
		
		final String projectName = configuration.getAttribute(XMLTLaunchTab.ATTR_PROJECT_NAME, "");
		final String outputDirPath = configuration.getAttribute(XMLTLaunchTab.ATTR_OUTPUT_DIR, "");
		final File outputDir = new File(outputDirPath);
		if (!outputDir.exists() || !outputDir.isDirectory()) {
			return;
		}
		Job launchJob = new Job("XMLT run (" + projectName + ")") {
			
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
				try {
					if (project.getNature(XMLTNature.NATURE_ID) == null)
						return Status.CANCEL_STATUS;
					project.accept(new IResourceVisitor() {
						
						@Override
						public boolean visit(IResource arg0) throws CoreException {
							if (!(arg0 instanceof IFile))
								return true;
							IFile file = (IFile) arg0;
							String ref = file.getProjectRelativePath().toString();
							if(file.getName().endsWith(".inst")) {
								Instance instance = null;
								try {
									instance = BuilderPlugin.getTemplateManager(project).loadInstance(ref);
								} catch (TemplateException e1) {
									throw new CoreException(Status.OK_STATUS);
								}
								Template template = instance.getTemplate();
								List<TemplateSection> sections = template.getSections();
								for (TemplateSection ts: sections) {
								}
							}
							return true;
						}
					});
				} catch (CoreException e) {
				}
				
				return Status.OK_STATUS;
			}
			
		};
		launchJob.setUser(true);
		launchJob.schedule();
	}
	
}
